﻿using System.Collections.Generic;
using System.Linq;

namespace Sidvall.Security
{
    public class PropertyItemCollection : System.Collections.ObjectModel.KeyedCollection<string, PropertyItem>
    {
        #region Public Members

        #region Add

        public void Add(string propertyName, int readAccessLevel, int writeAccessLevel)
        {
            var item = new PropertyItem()
            {
                PropertyName = propertyName,
                ReadAccessLevel = readAccessLevel,
                WriteAccessLevel = writeAccessLevel,
            };
            Add(item);
        }

        #endregion
        #region AddRange

        public void AddRange(int readAccessLevel, int writeAccessLevel, string propertyPrefix, params string[] propertyNames)
        {
            AddRange(readAccessLevel, writeAccessLevel, propertyPrefix, propertyNames.AsEnumerable());
        }
        public void AddRange(int readAccessLevel, int writeAccessLevel, string propertyPrefix, IEnumerable<string> propertyNames)
        {
            if (propertyNames == null)
                return;
            foreach (var propertyName in propertyNames)
            {
                if (string.IsNullOrWhiteSpace(propertyPrefix))
                    Add(propertyName, readAccessLevel, writeAccessLevel);
                else
                    Add(propertyPrefix + propertyName, readAccessLevel, writeAccessLevel);
            }
        }

        #endregion
        #region Merge

        public PropertyItem Merge(string propertyName, int readAccessLevel, int writeAccessLevel)
        {
            var item = FindItem(propertyName);
            if (item != null)
            {
                item.ReadAccessLevel = readAccessLevel;
                item.WriteAccessLevel = writeAccessLevel;
            }
            else
            {
                item = new PropertyItem()
                {
                    PropertyName = propertyName,
                    ReadAccessLevel = readAccessLevel,
                    WriteAccessLevel = writeAccessLevel,
                };
                Add(item);
            }
            return item;
        }

        #endregion
        #region FindItem

        public PropertyItem FindItem(string propertyName)
        {
            if (!string.IsNullOrWhiteSpace(propertyName))
            {
                if (Contains(propertyName))
                    return this[propertyName];
            }
            return null;
        }

        #endregion
        #region GetKeyForItem

        protected override string GetKeyForItem(PropertyItem item)
        {
            if (item == null)
                throw new System.ArgumentNullException(nameof(item));
            return item.PropertyName;
        }

        #endregion

        #endregion
    }
}
